﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using ThaireInvestmentWeb.BusinessDelegate;
using ThaireInvestmentWeb.Models;
using ThaireInvestmentWeb.Util;
using ThaireInvestmentWeb.WcfSerivce;

namespace ThaireInvestmentWeb.Controllers
{
    public class InstrumentController : Controller
    {
        //
        // GET: /Instrument/

        // String UserLogin = "TestUser2";

        private ServiceDelegate _service;
        public ServiceDelegate Service
        {
            get { return _service ?? (_service = new ServiceDelegate()); }
        }


        public ActionResult Index()
        {
            return View();
        }


        #region FixedIncomeSecurities

        #region Guarantee
        //public ActionResult FixedIncomeGuarantee(int purchaseID)
        //{
        //    var data = Service.GetFixIncomeSecuritiesTransactionScreenData(purchaseID);
        //    var model = FixedIncomeGuaranteeModel.Build(data);
        //    TempData["FixedIncomeGuaranteeModel"] = model;
        //    return View(model);
        //}
        public ActionResult FixedIncomeGuarantee(int purchaseID,int? transactionID)
        {
            var data = Service.GetFixIncomeSecuritiesTransactionScreenData(purchaseID, transactionID);
            var model = FixedIncomeGuaranteeModel.Build(data);
            TempData["FixedIncomeGuaranteeModel"] = model;
            return View(model);
        }

        [HttpPost]
        public ActionResult FixedIncomeGuarantee(FixedIncomeGuaranteeModel model)
        {
            var oldModel = (FixedIncomeGuaranteeModel)TempData["FixedIncomeGuaranteeModel"];
            if (ModelState.IsValid)
            {
                try
                {
                    if (!String.IsNullOrEmpty(model.BtnSave))
                    {
                        var operationData = model.ToFixIncomeSecuritiesTransaction();

                        if (model.UpdateMode)
                        {
                            oldModel.SetFixIncomeSecuritiesTransaction(
                                Service.UpdateFixIncomeSecuritiesTransaction(operationData));
                        }
                        else
                        {
                            oldModel.SetFixIncomeSecuritiesTransaction(
                                Service.InsertFixIncomeSecuritiesTransaction(operationData));
                        }
                        oldModel.UpdateMode = true;
                        ModelState.Clear();
                        ViewBagUtil.SetInfo(ViewBag, "การทำงานสมบูรณ์", "EditPurchase?purchaseID=" + model.PurcheseID);
                   
                    }
                    else
                    {
                        throw new Exception("Button save (BtnSave) is null.");
                    }

                }
                catch (Exception ex)
                {
                    ViewBagUtil.SetError(ViewBag, ex.Message, null);
                }
            }
            TempData["FixedIncomeGuaranteeModel"] = oldModel;
            return View(oldModel);
        }

        #endregion

        #region Sale
        /// <summary>
        /// init sale ,update mode sale
        /// </summary>
        /// <param name="purchaseID"></param>
        /// <param name="transactionID"></param>
        /// <returns></returns>
        public ActionResult FixedIncomeSale(int purchaseID, int? transactionID)
        {
            FixIncomeSecuritiesTransactionScreenData data = Service.GetFixIncomeSecuritiesTransactionScreenData(purchaseID, transactionID);
            FixedIncomeSaleModel model = FixedIncomeSaleModel.Build(data);
            if (transactionID.GetValueOrDefault() != 0)
            {
                model.UpdateMode = true;
            }
            TempData["FixedIncomeSaleModel"] = model;
            return View(model);
        }

        //public ActionResult EditFixedIncomeSale(int purchaseID,int transactionID)
        //{
        //    FixIncomeSecuritiesTransactionScreenData data = Service.GetFixIncomeSecuritiesTransactionScreenData(purchaseID, transactionID);
        //    FixedIncomeSaleModel model = FixedIncomeSaleModel.Build(data);
        //    TempData["FixedIncomeSaleModel"] = model;
        //    return View(model);
        //}
        public ActionResult FixedIncomeSaleFormAction(FixedIncomeSaleModel model)
        {
            FixedIncomeSaleModel oldModel = (FixedIncomeSaleModel)TempData["FixedIncomeSaleModel"];
            if (ModelState.IsValid)
            {
                ServiceDelegate service = new ServiceDelegate();
                try
                {
                    if (!String.IsNullOrEmpty(model.BtnSave))
                    {
                        FixIncomeSecuritiesTransaction operationData = model.ToFixIncomeSecuritiesTransaction();
                        CounterParties counter =
                            oldModel.ScreenData.CounterParties.Where(
                                x => x.CounterpartiesId == operationData.CounterpartyID.GetValueOrDefault()).
                                SingleOrDefault();
                        if (counter != null)
                            operationData.CounterpartyName = counter.CounterpartiesNameTh;
                        TypeOfPayment payment = oldModel.ScreenData.TypeOfPayment.Where( x => x.ID == operationData.TypeofpaymentID.GetValueOrDefault()).SingleOrDefault();
                        if (payment != null)
                            operationData.TypeofpaymentName = payment.Name;
                         FixIncomeSecuritiesTransaction result  = null;
                        if (model.UpdateMode)
                        {
                            result = service.UpdateFixIncomeSecuritiesTransaction(operationData);
                          
                        }
                        else
                        {
                            result = service.InsertFixIncomeSecuritiesTransaction(operationData);
                        }
                         oldModel.SetFixIncomeSecuritiesTransaction(result);
                        oldModel.UpdateMode = true;
                        ModelState.Clear();
                        return RedirectToAction("FixedIncomeSale", new {purchaseID = result.PurchaseID,transactionID =result.TransactionID });//. .PurcheseID,oldModel.tr
                    }
                    else
                    {
                        throw new Exception("Button save (BtnSave) is null.");
                    }
                }
                catch (Exception ex)
                {
                    ViewBagUtil.SetError(ViewBag, ex.Message, null);
                  
                }
                //FixIncomeSecuritiesTransactionScreenData data = service.GetFixIncomeSecuritiesTransactionScreenData(purchaseID);
                //FixedIncomeSaleModel model = FixedIncomeSaleModel.Build(data);
            }
            TempData["FixedIncomeSaleModel"] = oldModel;
            return View("FixedIncomeSale", oldModel);
        }

        public ActionResult GetInvolvedType(int id)
        {
            AddFixedIncomeModel model = (AddFixedIncomeModel)TempData["AddFixedIncomeModel"];

            InvolvedPartyType involve = model.ScreenData.InvolvedPartyType.Where(X => X.InvolvedPartyTypeId == id).SingleOrDefault();
            TempData["AddFixedIncomeModel"] = model;
            if (involve != null)
            {
                return Json(new { InvolvedPartyTypeReference = involve.InvolvedPartyTypeReference, InvolvedPartyTypeCode = involve.InvolvedPartyTypeCode });
            }
            else
            {
                return Json(new { InvolvedPartyTypeReference = "", InvolvedPartyTypeCode = "" });
            }
        }

        public ActionResult GetMaturityStatus(DateTime maturityDate)
        {
            AddFixedIncomeModel oldModel = (AddFixedIncomeModel)TempData["AddFixedIncomeModel"];

            String issutTerm = null;
            double year = Calculator.CalFixIncomeIssueTerm(maturityDate);
            if (year < 0)
                issutTerm = "N/A";
            else
                issutTerm = year.ToString("0.00");


            TempData["AddFixedIncomeModel"] = oldModel;
            if (maturityDate.Date >= DateTime.Now.Date)

                return Json(new { MaturityStatus = "Matured", IssuerTermDsp = issutTerm });
            else
                return Json(new { MaturityStatus = "Alive", IssuerTermDsp = issutTerm });
        }
        #endregion

        #region header
        /// <summary>
        /// หน้า manage เมนู FixedIncomeSecurittes
        /// </summary>
        /// <returns></returns>
        public ActionResult ManageFixedIncomeSecurittes()
        {
            var service = new ServiceDelegate();

            SearchFixedIncomeSecuritiesModel model = null;
            try
            {
                var data = service.GetFixedIncomeListScreenData();
                model = SearchFixedIncomeSecuritiesModel.BuildFixedIncomeModel(data);
            }
            catch (Exception ex)
            {
                model = new SearchFixedIncomeSecuritiesModel();
                //   ViewData["error"] = ex.Message;
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
              //  ModelState.AddModelError("", ex.Message);
            }
            TempData["SearchFixedIncomeSecuritiesModel"] = model;
            return View(model);
        }

        /// <summary>
        /// ค้นหา Header
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult SearchFormAction(SearchFixedIncomeSecuritiesModel model)
        {
            // ViewBag.MyScreenModel = model;
            var oldModel = (SearchFixedIncomeSecuritiesModel)TempData["SearchFixedIncomeSecuritiesModel"];

            try
            {
                oldModel.SelectedCompany = model.SelectedCompany;
                oldModel.SelectedIssuer = model.SelectedIssuer;
                oldModel.SelectedIssuerType = model.SelectedIssuerType;
                oldModel.Symbol = model.Symbol;
                oldModel.IssueTerm = model.IssueTerm;

                if (!String.IsNullOrEmpty(model.SearchBtn))
                {
                    oldModel.Result = SearchFixedIncomeSecurities(oldModel);
                    if (oldModel.Result == null || oldModel.Result.Count == 0)
                    {
                        ViewBagUtil.SetInfo(ViewBag, "ไม่พบข้อมูล", null);
                    
                    }
                }
                else if (!String.IsNullOrEmpty(model.ResetBtn))
                {
                    ModelState.Clear();
                    oldModel.ClearFilterAndData();
                }
                TempData["SearchFixedIncomeSecuritiesModel"] = oldModel;
            }
            catch (Exception ex)
            {
             //   ViewData["error"] = ex.Message;
                ViewBagUtil.SetInfo(ViewBag, ex.Message, null);
                // ModelState.AddModelError("", ex.Message);
            }
            //return View("fixedIncomeLIst", oldModel);
            return View("ManageFixedIncomeSecurittes", oldModel);
        }

        /// <summary>
        /// หน้า add header
        /// </summary>
        /// <returns></returns>
        public ActionResult AddfixedIncome()
        {
            var service = new ServiceDelegate();
            var scrData = service.GetFixedIncomeHeaderScreenData();
            var model = AddFixedIncomeModel.BuildModel(scrData);
            TempData["AddFixedIncomeModel"] = model;
            return View(model);
        }

        /// <summary>
        /// หน้า edit header
        /// </summary>
        /// <param name="fixedincomeID"></param>
        /// <returns></returns>
        public ActionResult EditFixedIncome(int fixedincomeID)
        {
            ModelState.Clear();
            if (fixedincomeID == 0)
            {
                return RedirectToAction("AddfixedIncome");

            }
            else
            {
                var service = new ServiceDelegate();
                var scrData = service.GetFixedIncomeHeaderScreenData();

                scrData.FixIncomeSecuritiesDTO = service.GetFixedIncomeSecurities(fixedincomeID);
                var model = AddFixedIncomeModel.BuildModel(scrData);
                model.UpdateMode = true;
                TempData["AddFixedIncomeModel"] = model;
                return View("AddfixedIncome", model);
            }
        }

        /// <summary>
        /// ค้นหา header
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private IList<FixIncomeSecuritiesHeader> SearchFixedIncomeSecurities(SearchFixedIncomeSecuritiesModel model)
        {
            return new ServiceDelegate().SearchFixedIncomeSecurities(model);
        }

        /// <summary>
        /// action สำหรับ insert or update header
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult AddfixedIncomeFormAction(AddFixedIncomeModel model,int? page)
        {

            var oldData = (AddFixedIncomeModel)TempData["AddFixedIncomeModel"];
            TempData["AddFixedIncomeModel"] = oldData;
             oldData.Data = model.Data;
            oldData.RatingHistory = model.RatingHistory;
            if (ModelState.IsValid)
            {

                if (!String.IsNullOrEmpty(model.SaveBtn))
                {

                    if (model.Data.LiquidityTierIiPercent.GetValueOrDefault() +
                        model.Data.LiquidityTierIPercent.GetValueOrDefault() +
                        model.Data.LiquidityLowLiquidityPercent.GetValueOrDefault() > 100)
                    {
                        ViewBagUtil.SetError(ViewBag, "มูลค่า % ของแต่ะละประเภท Liquidity รวมกันห้ามเกิน 100%", null);
                        //   ModelState.AddModelError("", "มูลค่า % ของแต่ะละประเภท Liquidity รวมกันห้ามเกิน 100%");
                        model = oldData;
                    }
                    else
                    {

                        try
                        {
                            model.Data.IssuerTerm = (decimal)Calculator.CalFixIncomeIssueTerm(model.Data.MaturityDate.GetValueOrDefault());
                            model.Data.IssuerTypeName = WebUtil.GetSelectionText(oldData.IssuerTypeList, model.SelectedIssuerType);
                            model.Data.IssuerName = WebUtil.GetSelectionText(oldData.IssuerList, model.SelectedIssuer.ToString());
                            model.Data.BondTypeName = WebUtil.GetSelectionText(oldData.BondTypeList, model.SelectedBondType.ToString());
                            model.Data.GuarantorName = WebUtil.GetSelectionText(oldData.GuarantorList, model.SelectedGuarantor.ToString());
                            model.Data.CompanyName = WebUtil.GetSelectionText(oldData.CompanyList, model.SelectedCompany.ToString());
                            model.Data.InvolvedPartyTypeName = WebUtil.GetSelectionText(oldData.InvolvedPartyTypeNameList, model.SelectedInvolvedPartyType.ToString());
                            model.Data.GuarantorTypeName = WebUtil.GetSelectionText(oldData.GuarantorTypeList, model.SelectedGuarantorTypeID);
                            model = SaveOrUpdateDataFixedIncomeHeader(model);
                            model.UpdateMode = true;
                            ModelState.Clear();
                            ViewBagUtil.SetInfo(ViewBag, "การบันทึกสมบูรณ์", null);
                            
                        }
                        catch (Exception ex)
                        {
                            ViewBagUtil.SetError(ViewBag, "การบันทึกผิดพลาด :" + ex.Message, null);
                            //   ModelState.AddModelError("", "การบันทึกผิดพลาด :" + ex.Message);

                        }
                    }
                }
                else
                {
                    ViewBagUtil.SetError(ViewBag, "Unknow Operation" , null);
                }
            }
            else
            {
                ViewBagUtil.SetError(ViewBag, "ModelState.Invalid" , null);
            }
            
            TempData["AddFixedIncomeModel"] = model;
            return View("AddFixedIncome", model);
        }

        /// <summary>
        /// insert or update header
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private AddFixedIncomeModel SaveOrUpdateDataFixedIncomeHeader(AddFixedIncomeModel model)
        {
            var data = (AddFixedIncomeModel)TempData["AddFixedIncomeModel"];
            FixIncomeSecuritiesDTO dto = null;
            if (model.UpdateMode)
            {
                dto = Service.UpdateFixIncomeHeader(model);
            }
            else
            {
                dto = Service.InsertFixIncomeHeader(model);
            }
            data.Data = dto.Header;
            data.RatingHistory = dto.RatingHistory;
            return data;
        }

        #endregion

        #region Purchase

        public ActionResult CouponTableAndAmortize(int purchaseID)
        {
            CouponTableAndAmortizeModel model = new CouponTableAndAmortizeModel();
            try
            {
                AmortizeScreenData data = ServiceFactory.GetService().GenerateAmortize(purchaseID);
                model.AmortizeData = data;
            }
            catch (Exception ex)
            {

                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            TempData["CouponTableAndAmortizeModel"] = model;
            return View(model);
        } 

       [HttpPost]
        public ActionResult CouponTableAndAmortize(CouponTableAndAmortizeModel model)
        {
            CouponTableAndAmortizeModel oldModel = (CouponTableAndAmortizeModel)TempData["CouponTableAndAmortizeModel"];
            if (!String.IsNullOrEmpty(model.BtnExportExcel))
            {
                String fileName = ExportAmortizeExcel(oldModel);
                String link = ConfigurationManager.AppSettings["ExcelServiceOutputUrl"] + fileName;
                return Redirect(link);
            }
            else
            {
                ViewBagUtil.SetError(ViewBag, "Unknow operation", null);
            }
            TempData["CouponTableAndAmortizeModel"] = oldModel;
            return View(oldModel);
        }

       private String ExportAmortizeExcel(CouponTableAndAmortizeModel oldModel)
       {
           if (oldModel.AmortizeData == null)
               throw new Exception("CouponTableAndAmortizeModel lost (ExportExcel)");
           ExcelWSService.ExcelWSClient client = new ExcelWSService.ExcelWSClient();
           client.Endpoint.ListenUri = new Uri(ConfigurationManager.AppSettings["ExcelServiceUrl"]);
           ExcelWSService.valueClass header = new ExcelWSService.valueClass();
           header.string1 = oldModel.Symbol;
           header.string2 = oldModel.AmortizeData.AmortizeHeader.TradeDate.GetValueOrDefault().ToString("dd/MM/yyyy");
           header.string3 = oldModel.AmortizeData.AmortizeHeader.MaturityDate.GetValueOrDefault().ToString("dd/MM/yyyy");
           header.double1 = (double)oldModel.AmortizeData.AmortizeHeader.ParValue.GetValueOrDefault();
           header.double2 = 0;
           header.double3 = (double)oldModel.AmortizeData.AmortizeHeader.DiscountPremium.GetValueOrDefault();
           header.double4 = (double)oldModel.AmortizeData.AmortizeHeader.AI.GetValueOrDefault();
           header.double5 = (double)oldModel.AmortizeData.AmortizeHeader.GrossPrice.GetValueOrDefault();
           header.double6 = (double)oldModel.AmortizeData.AmortizeHeader.ParValue.GetValueOrDefault();
           header.double7 = (double)oldModel.AmortizeData.AmortizeHeader.BookValue.GetValueOrDefault();
           header.double8 = (double)oldModel.AmortizeData.AmortizeHeader.IrrPerDay.GetValueOrDefault();
           header.double9 = (double)oldModel.AmortizeData.AmortizeHeader.Coupon.GetValueOrDefault();
           header.double10 = (double)oldModel.AmortizeData.AmortizeHeader.Yield.GetValueOrDefault();



           List<ExcelWSService.valueClass> detail = new List<ExcelWSService.valueClass>();
           foreach (var item in oldModel.AmortizeData.AmortizeDetailList)
           {
               ExcelWSService.valueClass value = new ExcelWSService.valueClass();
               value.double1 = item.Period.GetValueOrDefault();
               value.string1 = item.AmortizeDate.GetValueOrDefault().ToString("dd/MM/yyyy");
               value.double2 = item.NOOFDays.GetValueOrDefault();
               value.double3 = (double)item.Coupon.GetValueOrDefault();
               value.double4 = (double)item.Interest.GetValueOrDefault();
               value.double5 = (double)item.AmortiseOFInterest.GetValueOrDefault();
               value.double6 = (double)item.DiscountPremium.GetValueOrDefault();
               value.double7 = (double)item.BookValue.GetValueOrDefault();


               detail.Add(value);
           }



           return client.export1("amortize_01", header, detail.ToArray());
       }
        //public ActionResult GetPayValue(int? unit, decimal? par)
        //{
        //    if (unit == null || par == null)
        //        return null;
        //    var parvalue = unit.GetValueOrDefault()*par.GetValueOrDefault();
        //    var model = (AddFixedIncomePurchaseModel)TempData["AddFixedIncomePurchaseModel"];
        //    model.Purchase.ParValue = parvalue;
        //    TempData["AddFixedIncomePurchaseModel"] = model;
        //    return Json(new { ParValue = parvalue });
        //}

        /// <summary>
        /// หน้า add purchase
        /// </summary>
        public ActionResult AddFixedIncomePurchase(int fixedIncomeID)
        {
            var model = InitAddFixedIncomePurchaseModel(null);
            model.HeaderDto = Service.GetFixIncomeHeaderByID(fixedIncomeID);

            //assign TIME2MATURE
            model.Purchase.TIME2MATURE = CalTime2Mature(model.Header.MaturityDate);

            TempData["AddFixedIncomePurchaseModel"] = model;
            return View(model);
        }
        /// <summary>
        /// หน้า edit purchase
        /// </summary>
        public ActionResult EditPurchase(int purchaseID)
        {
            var model = InitAddFixedIncomePurchaseModel(null);
            var dto = Service.GetFixIncomePurchaseByID(purchaseID);
            model.Purchase = dto.Purhcase;

            //TODO: temp data for test 
            //model.Purchase.PurchaseValueTh = 6;

            model.HeaderDto = dto.Header;
            model.UpdateMode = true;
            TempData["AddFixedIncomePurchaseModel"] = model;
            return View("AddFixedIncomePurchase", model);
        }

        decimal? CalTime2Mature(DateTime? matureityDate)
        {
            /* case when 
                    FIXINCOMESECURITIES_HEADER.MATURITY_DATE <= getdate() then 0 		
               else 		
                    convert(decimal(12,2), DATEDIFF(m, FIXINCOMESECURITIES_HEADER.MATURITY_DATE , getdate())/12.00)
             */
            if (matureityDate.HasValue)
            {
                var start = matureityDate.GetValueOrDefault();
                DateTime end = Service.GetSystemDateTime();
                if (start <= end)
                    return 0;
                //find of diff month
                var diffMonths = (end.Month + end.Year * 12) - (start.Month + start.Year * 12) + 1;
                //find TIME2MATURE
                return diffMonths / 12;
            }
            return null;
        }

        // init model สำหรับ insert or update purchase
        AddFixedIncomePurchaseModel InitAddFixedIncomePurchaseModel(AddFixedIncomePurchaseModel model)
        {
            if (model == null)
                model = new AddFixedIncomePurchaseModel();

            var payTypes = Service.GetAllPaymentTypes();
            if (payTypes == null)
            {
                model.TypeOfPaymentList.Add(item: new SelectListItem() { Selected = false, Text = "Bathnet", Value = "1" });
                model.TypeOfPaymentList.Add(item: new SelectListItem() { Selected = false, Text = "Cheque", Value = "2" });
                model.TypeOfPaymentList.Add(item: new SelectListItem() { Selected = false, Text = "NET", Value = "3" });
                model.TypeOfPaymentList.Add(item: new SelectListItem() { Selected = false, Text = "Rollover", Value = "4" });
            }
            else
            {
                foreach (var o in payTypes)
                {
                    model.TypeOfPaymentList.Add(item: new SelectListItem() { Selected = false, Text = o.PaymentTypeName, Value = o.PaymentTypeId.ToString() });
                }
            }

            //select from COUNTERPARTY.COUNTERPARTY_NAME
            var cntParties = Service.GetAllCounterPaties();
            if (cntParties == null)
            {
                model.CounterPartyList.Add(item: new SelectListItem() { Selected = false, Text = "HSBC", Value = "1" });
                model.CounterPartyList.Add(item: new SelectListItem() { Selected = false, Text = "BBL", Value = "2" });
                model.CounterPartyList.Add(item: new SelectListItem() { Selected = false, Text = "KL", Value = "3" });
            }
            else
            {
                foreach (var o in cntParties)
                {
                    model.CounterPartyList.Add(item: new SelectListItem() { Selected = false, Text = o.CounterpartiesCodeName, Value = o.CounterpartiesId.ToString() });
                }
            }

            return model;
        }

        /// <summary>
        /// action สำหรรับ insert or update purchase
        /// </summary>
        [HttpPost]
        public ActionResult ExecuteForAddFixedIncomePurchase(AddFixedIncomePurchaseModel model, object arg)
        {
            var oldModel = (AddFixedIncomePurchaseModel)TempData["AddFixedIncomePurchaseModel"];
            if (ModelState.IsValid)
            {
                try
                {
                    if (!String.IsNullOrEmpty(model.SubmitBtn))
                    {
                        model.Purchase.FixincomesecuritiesHeaderId = model.Header.FixincomesecuritiesHeaderId;
                        if (model.UpdateMode)
                        {
                            oldModel.Purchase = Service.UpdateFixincomesecuritiesPurchase(model.Purchase);
                        }
                        else
                        {
                            oldModel.Purchase = Service.InsertFixedIncomePurchase(model.Purchase);
                        }
                        oldModel.UpdateMode = true;
                        ViewBagUtil.SetInfo(ViewBag, "การทำงานสมบูรณ์", null);
                        ModelState.Clear();
                    }
                    else
                    {
                        throw new Exception("Button save (BtnSave) is null.");
                    }
                }
                catch (Exception ex)
                {
                    ViewBagUtil.SetError(ViewBag, ex.Message, null);
      
                }
            }
            TempData["AddFixedIncomePurchaseModel"] = oldModel;
            return View("AddFixedIncomePurchase", oldModel);
        }

        #endregion


        #endregion


        #region Equity Securities
        //add logic for "Equity Securities" here


        #endregion

        #region Unit Trust
        //add logic for "Unit Trust" here


        #endregion

        #region Derivatives Securities
        //add logic for "Derivatives Securities" here


        #endregion

        #region Loans
        //add logic for "Loans" here


        #endregion

        #region Deposit at Financial Institutions
        //add logic for "Deposit at Financial Institutions" here


        #endregion


    }
}
